package com.itrui.TCP;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;


public class SocketClient {
    public static void main(String args[]) throws Exception {
        // 通过服务器ip地址和端口号与服务端建立连接
        //"127.0.0.1"==>ip地址
        //8899==>端口号
        Socket socket = new Socket("127.0.0.1", 8899);
        // 建立连接后获得输出流
        OutputStream outputStream = socket.getOutputStream();
        //传输的信息
        String message = "Hello.This is SocketClient";
        socket.getOutputStream().write(message.getBytes("UTF-8"));
        //单方面关闭输入输出流，不会造成socket关闭（）
        socket.shutdownOutput();

        InputStream inputStream = socket.getInputStream();
        byte[] bytes = new byte[1024];
        int len;
        StringBuilder sb = new StringBuilder();
        while ((len = inputStream.read(bytes)) != -1) {
            //注意指定编码格式，发送方和接收方一定要统一，建议使用UTF-8
            sb.append(new String(bytes, 0, len,"UTF-8"));
        }
        System.out.println("Get message from server: " + sb);

        inputStream.close();
        outputStream.close();
        socket.close();
    }
}


